package com.seecen.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.seecen.mapper.CompanyMapper;
import com.seecen.pojo.dto.ComplaintsDto;
import com.seecen.pojo.entity.Company;
import com.seecen.pojo.dto.MainPageDto;
import com.seecen.pojo.entity.Complaints;
import com.seecen.pojo.vo.ComplaintsDetailVo;
import com.seecen.pojo.vo.MainTitleVo;
import com.seecen.service.CompanyService;
import com.seecen.service.ComplaintsService;
import com.seecen.mapper.ComplaintsMapper;
import com.seecen.utils.*;
import com.seecen.utils.exception.BusinessException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import com.seecen.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
* @author lenovo
* @description 针对表【hm_complaints(投诉信息表)】的数据库操作Service实现
* @createDate 2025-10-16 14:21:38
*/
@Service
public class ComplaintsServiceImpl extends ServiceImpl<ComplaintsMapper, Complaints>
    implements ComplaintsService{

    @Autowired
    private  ComplaintsMapper complaintsMapper;
    @Autowired
    private CompanyService companyService;

    @Autowired
    private CompanyMapper companyMapper;

    //热门问题列表
    @Override
    public Result selectHotQuestions(String merchantName) {
        QueryWrapper<Complaints> wrapper = new QueryWrapper<>();
        wrapper.select("subject", "COUNT(*) as subjectCount")
                .eq("merchant_name", merchantName)
                .groupBy("subject")
                .orderByDesc("subjectCount")
                .last("LIMIT 19");  // 按主题数量降序排序
        List<Complaints> complaints = complaintsMapper.selectList(wrapper);
        System.out.println("complaints = " + complaints);
        final int TARGET_SIZE = 19;
        ArrayList<String> hotProblemTags = new ArrayList<>(TARGET_SIZE);

        // 步骤1: 提取投诉中的主题并创建快速查找Set
        Set<String> complaintSubjects = complaints.stream()
                .map(Complaints::getSubject)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());
        // 步骤2: 创建枚举中不重复主题的迭代器
        Iterator<String> uniqueEnumSubjects = Arrays.stream(ComplaintSubjectEnum.values())
                .map(ComplaintSubjectEnum::getSubject)
                .filter(subject -> !complaintSubjects.contains(subject))
                .iterator();
        // 步骤3: 先填充投诉数据中的主题
        int addedCount = 0;
        for (Complaints complaint : complaints) {
            if (addedCount >= TARGET_SIZE) {
                break;
            }
            if (complaint.getSubject() != null) {
                hotProblemTags.add(complaint.getSubject());
                addedCount++;
            }
        }
        // 步骤4: 用枚举中不重复的主题补充剩余位置
        while (addedCount < TARGET_SIZE && uniqueEnumSubjects.hasNext()) {
            hotProblemTags.add(uniqueEnumSubjects.next());
            addedCount++;
        }

        for (String hotProblemTag : hotProblemTags) {
            System.out.println("hotProblemTag = " + hotProblemTag);
        }
        HashMap hashMap = new HashMap();
        hashMap.put("hotProblemTags", hotProblemTags);
        return Result.ok(hashMap);
    }

    @Override
    public Result findComplaintsPage(MainPageDto dto) {
        Page<Complaints> page = new Page<>(dto.getPageNum(), dto.getPageSize());
        LambdaQueryWrapper<Complaints> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.select(
                Complaints::getComplaintId,
                Complaints::getUserId,
                Complaints::getMerchantName,
                Complaints::getSubject,
                Complaints::getTitle,
                Complaints::getDescription,
                Complaints::getStatus,
                Complaints::getCreateTime
        );

        String viewType = dto.getStatus(); // 现在 status 表示视图类型

        // 根据 viewType 决定是否加状态过滤
        if ("replied".equals(viewType)) {
            queryWrapper.eq(Complaints::getStatus, "replied");
        } else if ("resolved".equals(viewType)) {
            queryWrapper.eq(Complaints::getStatus, "resolved");
        }
        // "hot" 和 "latest" 不加状态过滤，查所有状态

        // 排序逻辑
        if ("hot".equals(viewType)) {
            queryWrapper.orderByDesc(Complaints::getClick);
        } else {
            // latest / replied / resolved 都按时间倒序
            queryWrapper.orderByDesc(Complaints::getCreateTime);
        }

        IPage<Complaints> resultPage = complaintsMapper.selectPage(page, queryWrapper);

        List<MainTitleVo> voList = resultPage.getRecords().stream()
                .map(complaint -> {
                    MainTitleVo vo = new MainTitleVo();
                    vo.setComplaintId(complaint.getComplaintId());
                    vo.setUserId(complaint.getUserId());
                    vo.setMerchantName(complaint.getMerchantName());
                    vo.setSubject(complaint.getSubject());
                    vo.setTitle(complaint.getTitle());
                    vo.setDescription(complaint.getDescription());
                    vo.setStatus(complaint.getStatus());
                    vo.setCreateTime(complaint.getCreateTime());
                    return vo;
                })
                .collect(Collectors.toList());

        Map<String, Object> map = new HashMap<>();
        map.put("pageInfo", voList);
        return Result.ok(map);
    }

    //热门要求列表
    @Override
    public Result selectHotRequires(String merchantName) {
        QueryWrapper<Complaints> wrapper = new QueryWrapper<>();
        wrapper.select("requirements", "COUNT(*) as RequirementCount")
                .eq("merchant_name", merchantName)
                .groupBy("requirements")
                .orderByDesc("RequirementCount")
                .last("LIMIT 15");  // 按主题数量降序排序
        List<Complaints> complaints = complaintsMapper.selectList(wrapper);
        final int TARGET_SIZE = 15;
        ArrayList<String> hotRequirementTags = new ArrayList<>(TARGET_SIZE);

        // 步骤1: 提取投诉中的主题并创建快速查找Set
        Set<String> complaintRequirements = complaints.stream()
                .map(Complaints::getRequirements)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());
        // 步骤2: 创建枚举中不重复主题的迭代器
        Iterator<String> uniqueEnumRequirements = Arrays.stream(ComplaintRequireEnum.values())
                .map(ComplaintRequireEnum::getRequirements)
                .filter(subject -> !complaintRequirements.contains(subject))
                .iterator();
        // 步骤3: 先填充投诉数据中的主题
        int addedCount = 0;
        for (Complaints complaint : complaints) {
            if (addedCount >= TARGET_SIZE) {
                break;
            }
            if (complaint.getRequirements() != null) {
                hotRequirementTags.add(complaint.getRequirements());
                addedCount++;
            }
        }
        // 步骤4: 用枚举中不重复的主题补充剩余位置
        while (addedCount < TARGET_SIZE && uniqueEnumRequirements.hasNext()) {
            hotRequirementTags.add(uniqueEnumRequirements.next());
            addedCount++;
        }

        for (String hotProblemTag : hotRequirementTags) {
            System.out.println("hotRequirementTags = " + hotProblemTag);
        }
        HashMap hashMap = new HashMap();
        hashMap.put("hotRequirementTags", hotRequirementTags);
        return Result.ok(hashMap);
    }

    // 查询投诉详细信息
    @Override
    public Result findComplaintsDetail(Integer cId) {
        Complaints complaints = complaintsMapper.selectById(cId);
        Integer companyId = complaints.getCompanyId();
        Company company = companyMapper.selectById(companyId);

        // 增加点击数
        complaints.setClick(complaints.getClick()+1);
        complaintsMapper.updateById(complaints);

        ComplaintsDetailVo detailVo = new ComplaintsDetailVo();
        detailVo.setUserId(complaints.getUserId());
        detailVo.setComplaintId(complaints.getComplaintId());
        detailVo.setCompanyName(company.getCompanyName());
        detailVo.setCompanyPicture(company.getCompanyPicture());
        detailVo.setSubject(complaints.getSubject());
        detailVo.setRequirements(complaints.getRequirements());
        detailVo.setStatus(complaints.getStatus());
        detailVo.setTitle(complaints.getTitle());
        detailVo.setCreateTime(complaints.getCreateTime());
        detailVo.setDescription(complaints.getDescription());
        detailVo.setAttachmentUrl(complaints.getAttachmentUrl());
        detailVo.setHideImage(complaints.getHideImage());

        HashMap hashMap = new HashMap();
        hashMap.put("detail", detailVo);
        return Result.ok(hashMap);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result InsertComplaints(ComplaintsDto complaintsDto) {
        Complaints complaints = new Complaints();
        BeanUtils.copyProperties(complaintsDto, complaints);
        complaints.setCreateTime(new Date());
        complaints.setUpdateTime(new Date());
        complaints.setStatus("pending");
        complaints.setClick(0);
        Result result = companyService.InsertComplaintsCountByName(complaints.getMerchantName());
        if(result.getCode()!=200){
            throw new BusinessException(ResultCode.SUBMISSION_FAILED.getCode(), ResultCode.SUBMISSION_FAILED.getMessage());
        }
        int insert = complaintsMapper.insert(complaints);
        if (insert <= 0) {
            throw new BusinessException(ResultCode.SUBMISSION_FAILED.getCode(), ResultCode.SUBMISSION_FAILED.getMessage());
        }
        return Result.ok("提交成功");
    }

    @Override
    public Result findComplaintsPageByCompanyId(MainPageDto mainPageDto) {
        Page<Complaints> page = new Page<>(mainPageDto.getPageNum(), mainPageDto.getPageSize());
        LambdaQueryWrapper<Complaints> queryWrapper = new LambdaQueryWrapper<>();

        // 必须根据 companyId 查询
        queryWrapper.eq(Complaints::getCompanyId, mainPageDto.getCompanyId());

        String viewType = mainPageDto.getStatus(); // status 表示视图类型

        // 根据 viewType 决定是否加状态过滤
        if ("replied".equals(viewType)) {
            queryWrapper.eq(Complaints::getStatus, "replied");
        } else if ("resolved".equals(viewType)) {
            queryWrapper.eq(Complaints::getStatus, "resolved");
        }
        // "latest" 或其他值（包括 all）不加状态过滤，查所有状态

        // 排序逻辑：hot 按点击量，其余按时间倒序
        if ("hot".equals(viewType)) {
            queryWrapper.orderByDesc(Complaints::getClick);
        } else {
            queryWrapper.orderByDesc(Complaints::getCreateTime);
        }

        IPage<Complaints> resultPage = complaintsMapper.selectPage(page, queryWrapper);

        List<MainTitleVo> voList = resultPage.getRecords().stream()
                .map(complaint -> {
                    MainTitleVo vo = new MainTitleVo();
                    vo.setComplaintId(complaint.getComplaintId());
                    vo.setUserId(complaint.getUserId());
                    vo.setMerchantName(complaint.getMerchantName());
                    vo.setSubject(complaint.getSubject());
                    vo.setTitle(complaint.getTitle());
                    vo.setDescription(complaint.getDescription());
                    vo.setStatus(complaint.getStatus());
                    vo.setCreateTime(complaint.getCreateTime());
                    return vo;
                })
                .collect(Collectors.toList());

        Map<String, Object> map = new HashMap<>();
        map.put("pageInfo", voList);
        return Result.ok(map);
    }
}




